﻿using NthDownload.Contracts.Plugins.BandwidthProviders;
using NthDownload.BandwidthProviderPlugins.ViewModels;
using NthDownload.Contracts;
using NthDownload.Common.Mapping;

namespace NthDownload.BandwidthProviderPlugins
{
    public class SpeedLimitBandwidthProviderUIService : IBandwidthProviderUIService
    {
        private readonly IBandwidthProviderFactory _factory;

        public SpeedLimitBandwidthProviderUIService(IBandwidthProviderFactory factory)
        {
            _factory = factory;
        }

        public ViewModelResults NewBandwidthProvider(out IBandwidthProvider bandwidthProvider)
        {
            bandwidthProvider = null;
            IBandwidthProvider newBandwidthProvider = _factory.CreateBandwidthProvider();

            SpeedLimitBandwidthProviderDetailsViewModel speedLimitBandwidthProviderDetailsViewModel = new SpeedLimitBandwidthProviderDetailsViewModel(newBandwidthProvider);
            speedLimitBandwidthProviderDetailsViewModel.NavigationService.ShowDialog(speedLimitBandwidthProviderDetailsViewModel, false);

            if (speedLimitBandwidthProviderDetailsViewModel.Result == ViewModelResults.Save)
            {
                bandwidthProvider = newBandwidthProvider;   
            }

            return speedLimitBandwidthProviderDetailsViewModel.Result;           
        }

        public ViewModelResults EditBandwidthProvider(IBandwidthProvider bandwidthProvider)
        {
            IBandwidthProvider clonedBandwidthProvider = (IBandwidthProvider)ObjectMappingService.Clone(bandwidthProvider);
            SpeedLimitBandwidthProviderDetailsViewModel speedLimitBandwidthProviderDetailsViewModel = new SpeedLimitBandwidthProviderDetailsViewModel(clonedBandwidthProvider);

            speedLimitBandwidthProviderDetailsViewModel.NavigationService.ShowDialog(speedLimitBandwidthProviderDetailsViewModel, false);

            if (speedLimitBandwidthProviderDetailsViewModel.Result == ViewModelResults.Save)
            {
                ObjectMappingService.Update(clonedBandwidthProvider, bandwidthProvider);
            }

            return speedLimitBandwidthProviderDetailsViewModel.Result;
        }
    }
}
